import os
from common.settings import ROOT_PATH, logger
from utils.otherUtils.file_control import check_file_path


class TestCaseAutomaticGeneration:

    def __init__(self, api_common_info_file_path: str = None, api_file_path: str = None, project_name: str = None,
                 api_name: str = None, is_upload_file_api: bool = None):
        self.api_common_info_file_path = api_common_info_file_path
        self.api_file_path = api_file_path
        self.project_name = project_name
        self.api_name = api_name
        self.is_upload_file_api = is_upload_file_api
        self.allure_epic = ''
        self.allure_feature = ''
        self.class_name = 'Test'
        self.function_name = 'test_'
        self.path = ''

    def check_params(self) -> None:
        if not self.api_common_info_file_path:
            raise ValueError('配置文件路径为空')
        if not self.api_file_path:
            raise ValueError('接口定义文件路径为空')
        if not self.project_name:
            raise ValueError('项目名称为空')
        if not self.api_name:
            raise ValueError('接口名称为空')

    def get_allure_info(self) -> None:
        allure_lst = check_file_path(self.api_file_path).split(os.sep)
        self.allure_feature = allure_lst[-1].split('.')[0]
        self.allure_epic = allure_lst[-2]

    def get_name(self) -> None:
        name_lst = self.api_name.split('_')
        for item in name_lst:
            self.class_name += item.capitalize()
            self.function_name += item + '_'

    def is_file_exists(self) -> None:
        self.path = os.path.join(os.path.join(os.path.join(os.path.join(ROOT_PATH, 'testcase'), self.allure_epic),
                                 'single_api', f'{self.function_name[:-1]}.py'))
        if os.path.exists(self.path):
            raise ValueError(f'{self.path}已存在')

    def write_testcase_file(self) -> None:
        self.check_params()
        self.get_allure_info()
        self.get_name()
        self.is_file_exists()

        get_response = 'request_handler.run(excel_row[ExcelHead.REQUEST_PARAMS.value])'
        if self.is_upload_file_api:
            get_response = 'request_handler.run(excel_row[ExcelHead.REQUEST_PARAMS.value], ' \
                           'excel_row[ExcelHead.UPLOAD_FILE.value])'

        page = f'''import pytest
import allure
from utils.readFileUtils.yaml_control import YamlHandler
from utils.readFileUtils.excel_control import ExcelHandler
from utils.requestUtils.request_control import RequestHandler
from utils.assertUtils.assert_control import AssertHandler
from common.constant import ExcelHead

api_info = YamlHandler('{self.api_common_info_file_path}', '{self.api_file_path}', '{self.project_name}', '{self.api_name}').run()
excel_row_lst = ExcelHandler(api_info).get_excel_data()
request_handler = RequestHandler(api_info)


@allure.epic('{self.allure_epic}')
@allure.feature('{self.allure_feature}')
class {self.class_name}:
    
    @allure.story('{self.api_name}')
    @pytest.mark.parametrize('excel_row', excel_row_lst)
    def {self.function_name[:-1]}(self, excel_row):
        response = {get_response}
        AssertHandler(api_info, response, excel_row[ExcelHead.CHECK_POINT.value]).run()


if __name__ == '__main__':
    pytest.main(['{self.function_name[:-1]}.py', '-s', '-W', 'ignore:Module already imported:pytest.PytestWarning'])
'''

        with open(self.path, 'w', encoding='utf-8') as file:
            file.write(page)
            logger.info(f'{self.path} 测试用例生成完毕')


if __name__ == '__main__':
    # 第一个参数：接口公共信息文件路径，第二个参数：接口定义文件路径，第三个参数：环境/平台名称，第四个参数：接口名称
    obj = TestCaseAutomaticGeneration('common/api_common_info.yaml', 'api_detail/bilibili/search.yaml', 'bilibili', 'search_all_v2')
    obj.write_testcase_file()
